package com.dangs.autotest.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.text.TextUtils;
import android.widget.VideoView;

import com.dangs.autotest.service.FloatService;
import com.dangs.autotest.tool.L;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

class StaticBroadcastReceiver extends BroadcastReceiver {
    final String TAG = "StaticBroadcastReceiver";
    public static String targetPath;
    static final String TARGET_FILE = "dangs_auto_test_";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        L.i(TAG, "onReceive:" + action);
        L.i(TAG, "context:" + context.toString() + ", app context:" + context.getApplicationContext());
        if (Intent.ACTION_MEDIA_MOUNTED.equals(action)) {
            targetPath = getTargetFile(intent.getData().toString());
        } else if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {

        }
        context.startService(new Intent(context, FloatService.class));
    }


    private String getTargetFile(String Uri) {
        if (Uri == null || !Uri.startsWith("file://")) {
            return "";
        }
        String rootDir = Uri.substring("file://".length());
        File file = new File(rootDir);
        List<File> targetFiles = new ArrayList<>();
        if (file.exists() && file.isDirectory()) {
            for (File f : file.listFiles()) {
                String fileName = f.getName();
                if (!TextUtils.isEmpty(fileName) && fileName.startsWith(TARGET_FILE)) {
                    L.i(TAG, "find likely file:" + fileName);
                    targetFiles.add(f);
                    String currentModel = Build.MODEL.toLowerCase().replace(" ", "");
                    int index = fileName.lastIndexOf(TARGET_FILE) + TARGET_FILE.length();
                    if (index + currentModel.length() <= fileName.length()) {
                        String model = fileName.substring(index, index + currentModel.length());
                        L.i(TAG, "current model:" + currentModel + ", the target model:" + model);
                        if (model.equalsIgnoreCase(currentModel)) {
                            return f.getAbsolutePath();
                        }
                    }
                }
            }
            if (targetFiles.size() > 0) {
                L.w(TAG, "find target file, but is not the best one");
                return targetFiles.get(0).getAbsolutePath();
            }
        }
        return "";
    }
}
